package com.showcai.core.filter;

import com.showcai.core.util.ResposeUtil;
import com.showcai.log.LogFactory;
import com.showcai.myRunTime.MyRunTimeExcption;
import com.showcai.result.ResultObj;
import com.showcai.result.ReturnCode;
import com.showcai.service.VerifyService;
import com.showcai.tools.json.JsonHandler;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Baggio on 2018-2-2.
 */
public class VerifyFilter extends OncePerRequestFilter  {
    protected Logger logger = LogFactory.getLogger(getClass());
    @Autowired
    VerifyService verifyService;


    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
           String userAgent = request.getHeader("user-agent");
        logger.info("userAgent is====>>"+userAgent);

        // 不过滤的uri
        String[] notFilter = new String[]{"/static","/sync",".apk",
                "/createToken"};
        System.out.println("===========================>>>>>>>>>>>>>>>>>>>>>doFilterInternal>>>>>>>>>>>>>>>>>>>>>>>");

        // 请求的uri
        String uri = request.getRequestURI();


        logger.info("url is=======================>"+uri);
        // 是否过滤
        boolean doFilter = true;

        for (String s : notFilter) {
            if (uri.indexOf(s) != -1) {
                // 如果uri中包含不过滤的uri，则不进行过滤
                doFilter = false;
                break;
            }
        }

        if (doFilter) {

            System.out.println("====================true===================================>>>>>>>>>>>>>>");
            ResultObj resultObj = new ResultObj(ReturnCode.SYSTEM_ERRO);
            //String token = request.getParameter("token");//
            String url = uri.replaceFirst("/api/","");
           logger.info(url);
            try {
                HttpServletRequest req = (HttpServletRequest) request;
                ServletContext sc = req.getSession().getServletContext();
                XmlWebApplicationContext cxt = (XmlWebApplicationContext) WebApplicationContextUtils.getWebApplicationContext(sc);

                if (cxt != null && cxt.getBean("verifyService") != null && verifyService == null) {
                    verifyService = (VerifyService) cxt.getBean("verifyService");
                }
                String jj=verifyService.verify(url);
                logger.info(jj);

                Integer p=jj.indexOf("?");
                String newUrl="/"+ jj.substring(0,p>0?p:jj.length());
                String parameterStr=p>0?jj.substring(p+1):"";
                logger.info("parm====????"+parameterStr);
                logger.info("newUrl====>"+newUrl);
                request.getParameterMap();
                MyHttpServletRequestWrapper myHttpServletRequestWrapper = new MyHttpServletRequestWrapper(request,newUrl);
                String[] pp=parameterStr.split("&");
                for (String ppp:pp
                     ) {
                    System.out.println(ppp);
                    String[] a=ppp.split("=");
                    if(a.length>1){
                        myHttpServletRequestWrapper.addParameter(a[0],a[1]);
                    }
                }

                filterChain.doFilter(myHttpServletRequestWrapper, response);
                return;
               /* if (verifyService.verify(token)) {
                    System.out.println("============tongguo===========================================>>>>>>>>>>>>>>");
                    filterChain.doFilter(request, response);
                    return;
                }*/
            } catch (MyRunTimeExcption myRunTimeExcption) {
                myRunTimeExcption.printStackTrace();
                resultObj.setCode(myRunTimeExcption.getErroCode());
                resultObj.setMsg(myRunTimeExcption.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            ResposeUtil.writeContent(JsonHandler.objectToJson(resultObj), response);
            return;
        }
        // 如果不执行过滤，则继续
        filterChain.doFilter(request, response);
    }
}
